<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-item :labelCol="{ span: 5 }" :wrapperCol="{ span: 15 }" label="申请人">
              <x-select-user-by-dep
                :multi="false"
                v-decorator="['applierId', validatorRules.applierId]"
                @selected="setUser"
                :disabled="!editable || editableFiexd['applierId']"
              ></x-select-user-by-dep>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="申请金额" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                type="number"
                prefix="￥"
                v-decorator="['applyAmount', validatorRules.applyAmount]"
                :disabled="!editable || editableFiexd['applyAmount']"
                placeholder="请输入申请金额"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date
                placeholder="申请时间"
                :disabled="!editable || editableFiexd['createTime']"
                v-decorator="['createTime', validatorRules.createTime]"
                :trigger-change="true"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="原因" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea
                rows="4"
                :maxLength="255"
                placeholder="最多可以输入255个字符"
                v-decorator="['reason', validatorRules.reason]"
                :disabled="!editable || editableFiexd['applyAmount']"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="图片" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-image-upload
                :disabled="!editable || editableFiexd['pics']"
                text="上传图片"
                v-model="imageList"
                bizPath="fundapply"
                :isMultiple="true"
              ></j-image-upload>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="附加" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-upload
                v-model="fileList"
                :disabled="!editable || editableFiexd['enclosures']"
                text="上传文件"
                bizPath="fundapply"
              ></j-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
  </a-spin>
</template>

<script>
import moment from 'moment'
import { httpAction, getAction } from '@/api/manage'
import pick from 'lodash.pick'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import JDate from '@/components/jeecg/JDate'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
import XSearchUser from '@/components/extends/XSearchUser'
import XSelectUserByDep from '@/components/extends/XSelectUserByDep'
import JImageUpload from '@/components/jeecg/JImageUpload'
import JUpload from '@/components/jeecg/JUpload'

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}
export default {
  name: 'FundApplyForm',
  components: {
    JFormContainer,
    JDate,
    JDictSelectTag,
    JSelectDepart,
    XSearchUser,
    XSelectUserByDep,
    JImageUpload,
    JUpload
  },
  model: {
    prop: 'data',
    event: 'onchange'
  },
  props: {
    dataId: String,
    //流程表单data
    data: {
      type: Object,
      default: () => {},
      required: false
    },
    //表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    editable: {
      type: Boolean,
      default: true
    },
    editableFiexd: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      userDisabled: false,
      BaseUrl: window._CONFIG['domianURL'],
      previewVisible: false,
      previewImage: '',
      imageList: [],
      fileList: [],
      form: this.$form.createForm(this),
      formData: {
        createTime: null
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {
        applierId: {
          rules: [{ required: true, message: '请选择申请人!' }]
        },
        applyAmount: {
          rules: [{ required: true, message: '请输入申请金额!' }]
        },
        reason: {
          rules: [{ required: true, message: '请输入申请原因!' }]
        },
        createTime: {
          rules: [{ required: true, message: '请选择申请日期！' }]
        }
      },
      url: {
        add: '/fundApply/add',
        edit: '/fundApply/edit',
        queryById: '/fundApply/queryById'
      }
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }
  },
  watch: {
    'formData.pics'(nv, ov) {
      this.imageList = nv || ''
    },
    'formData.enclosures'(nv, ov) {
      this.fileList = nv || ''
    },
    visible(nv, ov) {
      if (!nv) {
        this.formData = {}
      }
    },
    data: {
      handler(nv, ov) {
        this.formData = nv
      },
      immediate: true,
      deep: true
    },
    formData: {
      handler(nv, ov) {
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(nv, 'name', 'sysOrgCode','directorId','dismissTime', 'instructorId'))
        })
        this.$emit('onchange', nv)
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    //如果是流程中表单，则需要加载流程表单data
    this.getData(this.dataId)
  },
  methods: {
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    add() {
      this.userDisabled = false
      this.open({})
    },
    apply(data) {
      this.userDisabled = true
      this.open(
        Object.assign({}, data, {
          workflowModel: {
            operation: 'start'
          }
        })
      )
    },
    edit(record) {
      this.userDisabled = true
      this.open(record)
    },
    open(record) {
      this.form.resetFields()
      this.formData = Object.assign({}, record)
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.formData, 'applierId', 'applyAmount', 'reason', 'createTime'))
      })
      if(record.id) this.getData(record.id)
    },
    setUser(data) {
      this.formData.realname = data.name
    },
    //渲染流程表单数据
    getData(id) {
      if (id) {
        let params = { id}
        getAction(this.url.queryById, params).then(res => {
          if (res.success) {
            this.formData = Object.assign({},this.formData,res.result)
            this.$nextTick(() => {
              this.form.setFieldsValue(pick(this.formData, 'applierId', 'applyAmount', 'reason', 'createTime'))
            })
          }
        })
      }
    },
    submitForm() {
      const that = this
      // 触发表单验证
      return new Promise(function(resolve, reject) {
        that.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!that.formData.id) {
              httpurl += that.url.add
              method = 'post'
            } else {
              httpurl += that.url.edit
              method = 'put'
            }
            let formData = Object.assign(that.formData, values)
            formData.createTime = moment(formData.createTime).valueOf()
          
            if (that.fileList.length) {
              formData.enclosures = that.fileList
            } else {
              formData.enclosures = ''
            }
            if (that.imageList.length) {
              formData.pics = that.imageList
            } else {
              formData.pics = ''
            }
            httpAction(httpurl, formData, method)
              .then(res => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                  resolve('ok')
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.confirmLoading = false
              })
          } else {
            console.log(err)
            reject(null)
          }
        })
      })
    },
    popupCallback(row) {
      this.form.setFieldsValue(pick(row, 'applierId', 'applyAmount', 'reason', 'createTime'))
    }
  }
}
</script>
